import { Card, Button, Steps, Input, Form, Select, Switch, Divider, Alert, message } from 'antd';
import { motion } from 'framer-motion';
import { Share2, Download, Settings, Globe, Shield, CheckCircle, FolderOpen } from 'lucide-react';
import { open } from '@tauri-apps/api/dialog';
import { invoke } from '@tauri-apps/api/tauri';
import { listen } from '@tauri-apps/api/event';
import { useState, useEffect } from 'react';
import LogViewer from '../components/LogViewer';

const { Step } = Steps;
const { Option } = Select;

const FrpSetup = () => {
  const [installPath, setInstallPath] = useState('');
  const [currentStep, setCurrentStep] = useState(0);
  const [logs, setLogs] = useState<string[]>([]);
  const [isInstalling, setIsInstalling] = useState(false);
  const [form] = Form.useForm();

  // 监听来自 Rust 后端的日志事件
  useEffect(() => {
    const unlistenLog = listen('frp-log', (event) => {
      const logMessage = event.payload as string;
      setLogs(prev => [...prev, logMessage]);
      
      // 检查是否是错误信息
      if (logMessage.includes('失败') || logMessage.includes('错误') || logMessage.includes('Error')) {
        setIsInstalling(false); // 停止 loading 状态
      }
      
      // 检查是否下载完成
      if (logMessage.includes('FRP 安装完成！')) {
        setIsInstalling(false);
        setCurrentStep(2); // 进入配置步骤
      }
    });

    return () => {
      unlistenLog.then(f => f());
    };
  }, []);

  // 检查安装状态
  useEffect(() => {
    const checkInstallStatus = async () => {
      try {
        const config = await invoke('get_frp_config') as any;
        if (config[1]) { // frp_installed
          setInstallPath(config[0]); // frp_dir
          setCurrentStep(2); // 直接跳转到配置页面
          
          // 加载现有的 FRP 配置
          loadFrpConfig();
        }
      } catch (error) {
        console.error('检查 FRP 安装状态失败:', error);
      }
    };
    
    checkInstallStatus();
  }, []);

  // 加载 FRP 配置
  const loadFrpConfig = async () => {
    try {
      const frpConfig = await invoke('get_frp_config_all') as Record<string, string>;
      
      // 设置表单默认值
      form.setFieldsValue({
        serverAddr: frpConfig.server_addr || '',
        serverPort: frpConfig.server_port || '',
        authToken: frpConfig.auth_token || '',
        enableMapping: frpConfig.enable_mapping === 'true',
        localUdpPort: frpConfig.local_udp_port || '',
        remoteUdpPort: frpConfig.remote_udp_port || '',
        localTcpPort: frpConfig.local_tcp_port || '',
        remoteTcpPort: frpConfig.remote_tcp_port || ''
      });
    } catch (error) {
      console.error('加载 FRP 配置失败:', error);
    }
  };

  // 检查路径是否包含中文字符
  const hasChineseCharacters = (path: string) => {
    return /[\u4e00-\u9fff]/.test(path);
  };

  const handleBrowseFolder = async () => {
    try {
      const selected = await open({
        directory: true,
        multiple: false,
        title: '选择 FRP 安装目录'
      });
      
      if (selected && typeof selected === 'string') {
        // 检查是否包含中文字符
        if (hasChineseCharacters(selected)) {
          message.error('安装路径不能包含中文字符，请选择不包含中文的目录！');
          setInstallPath('');
          return;
        }
        
        setInstallPath(selected);
      }
    } catch (error) {
      console.error('选择目录失败:', error);
    }
  };

  // 处理输入框手动输入
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    
    // 检查是否包含中文字符
    if (hasChineseCharacters(value)) {
      message.error('安装路径不能包含中文字符！');
      setInstallPath('');
      return;
    }
    
    setInstallPath(value);
  };

  // 下载 FRP 功能
  const downloadFrp = async () => {
    try {
      setIsInstalling(true);
      setLogs([]);
      
      console.log('开始调用后端 download_frp 命令，安装路径:', installPath);
      
      // 调用后端的 download_frp 命令
      const result = await invoke('download_frp', { frpDir: installPath });
      
      console.log('后端命令执行完成，结果:', result);
      
      // 注意：这里不设置 setIsInstalling(false)，因为下载过程是异步的
      // 真正的完成状态由事件监听器处理
      
    } catch (error) {
      console.error('下载失败:', error);
      message.error(`下载失败: ${error}`);
      setLogs(prev => [...prev, `错误: ${error}`]);
      setIsInstalling(false); // 只有出错时才停止 loading
    }
  };

  // 保存配置
  const saveConfig = async () => {
    try {
      const values = await form.validateFields();
      console.log('保存配置:', values);
      
      // 构建 FRP 配置 HashMap
      const frpConfig: Record<string, string> = {
        server_addr: values.serverAddr,
        server_port: values.serverPort,
        enable_mapping: values.enableMapping ? 'true' : 'false'
      };
      
      // 添加可选的认证令牌
      if (values.authToken) {
        frpConfig.auth_token = values.authToken;
      }
      
      // 添加端口映射配置
      if (values.enableMapping) {
        // 验证端口配置
        if (!values.localUdpPort || !values.remoteUdpPort) {
          message.error('请填写完整的 UDP 端口配置');
          return;
        }
        if (!values.localTcpPort || !values.remoteTcpPort) {
          message.error('请填写完整的 TCP 端口配置');
          return;
        }
        
        frpConfig.local_udp_port = values.localUdpPort;
        frpConfig.remote_udp_port = values.remoteUdpPort;
        frpConfig.local_tcp_port = values.localTcpPort;
        frpConfig.remote_tcp_port = values.remoteTcpPort;
      }
      
      console.log('保存的 FRP 配置:', frpConfig);
      
      // 保存配置到 HashMap
      await invoke('set_frp_config_all', { frpConfig });
      
      // 生成 FRP 配置文件
      await invoke('generate_frp_config');
      
      message.success('配置保存成功！');
      // 移除跳转到完成步骤，直接结束
    } catch (error) {
      console.error('保存配置失败:', error);
      message.error('配置保存失败，请检查输入');
    }
  };

  // 处理下一步按钮
  const handleNext = async () => {
    if (currentStep === 0) {
      if (!installPath.trim()) {
        message.error('请选择安装目录！');
        return;
      }
      setCurrentStep(1);
      await downloadFrp();
    } else if (currentStep === 2) {
      await saveConfig();
    }
  };

  // 处理上一步按钮
  const handlePrev = () => {
    if (currentStep > 0) {
      setCurrentStep(currentStep - 1);
    }
  };

  // 渲染不同步骤的内容
  const renderStepContent = () => {
    switch (currentStep) {
      case 0:
        return (
          <Card className="card" style={{ background: '#262626' }}>
            <Form layout="vertical" className="space-y-6">
              <Form.Item 
                label="安装目录" 
                name="installPath"
                rules={[{ required: true, message: '请选择安装目录' }]}
              >
                <Input.Group compact>
                  <Input 
                    placeholder="C:\\Frp" 
                    value={installPath}
                    onChange={handleInputChange}
                    style={{ width: 'calc(100% - 70px)' }}
                    className="bg-dark-secondary border-dark-border text-text-primary"
                  />
                  <Button 
                    className="btn-secondary" 
                    onClick={handleBrowseFolder}
                    style={{ 
                      width: '60px',
                      height: '40px',
                      marginLeft: '8px'
                    }}
                  >
                    浏览
                  </Button>
                </Input.Group>
              </Form.Item>
            </Form>
          </Card>
        );
      case 1:
        return (
          <LogViewer 
            logs={logs}
            title="FRP 下载日志"
            height={400}
          />
        );
      case 2:
        return (
          <div className="space-y-6">
            <Alert
              message="配置说明"
              description="FRP 是一个高性能的反向代理应用，可以帮助您轻松地进行内网穿透，对外网提供服务。"
              type="info"
              showIcon
              className="mb-6"
              icon={<Globe size={16} />}
            />

            <Form form={form} layout="vertical" className="space-y-6">
              <Card title="服务器配置" className="card" style={{ background: '#262626' }}>
                <Form.Item 
                  label="FRP 服务器地址" 
                  name="serverAddr"
                  rules={[{ required: true, message: '请输入服务器地址' }]}
                >
                  <Input 
                    placeholder="82.156.140.24"
                    className="bg-dark-secondary border-dark-border text-text-primary"
                    prefix={<Globe size={16} className="text-accent-500" />}
                  />
                </Form.Item>

                <Form.Item 
                  label="服务器端口" 
                  name="serverPort"
                  rules={[{ required: true, message: '请输入服务器端口' }]}
                >
                  <Input 
                    placeholder="7000"
                    className="bg-dark-secondary border-dark-border text-text-primary"
                    prefix={<Share2 size={16} className="text-accent-500" />}
                  />
                </Form.Item>

                <Form.Item 
                  label="认证令牌" 
                  name="authToken"
                >
                  <Input.Password 
                    placeholder="请输入认证令牌（可选）"
                    className="bg-dark-secondary border-dark-border text-text-primary"
                    prefix={<Shield size={16} className="text-accent-500" />}
                  />
                </Form.Item>
              </Card>

              <Card title="端口映射配置" className="card" style={{ background: '#262626' }}>
                <Form.Item 
                  label="SCUM 游戏端口 (UDP)" 
                >
                  <Input.Group compact>
                    <Form.Item 
                      name="localUdpPort" 
                      noStyle
                      rules={[
                        ({ getFieldValue }) => ({
                          validator(_, value) {
                            if (!getFieldValue('enableMapping') || value) {
                              return Promise.resolve();
                            }
                            return Promise.reject(new Error('请输入本地端口'));
                          },
                        }),
                      ]}
                    >
                      <Input 
                        placeholder="7777"
                        style={{ width: '50%' }}
                        className="bg-dark-secondary border-dark-border text-text-primary"
                      />
                    </Form.Item>
                    <Form.Item 
                      name="remoteUdpPort" 
                      noStyle
                      rules={[
                        ({ getFieldValue }) => ({
                          validator(_, value) {
                            if (!getFieldValue('enableMapping') || value) {
                              return Promise.resolve();
                            }
                            return Promise.reject(new Error('请输入远程端口'));
                          },
                        }),
                      ]}
                    >
                      <Input 
                        placeholder="远程端口"
                        style={{ width: '50%' }}
                        className="bg-dark-secondary border-dark-border text-text-primary"
                      />
                    </Form.Item>
                  </Input.Group>
                </Form.Item>

                <Form.Item 
                  label="SCUM 查询端口 (TCP)" 
                >
                  <Input.Group compact>
                    <Form.Item 
                      name="localTcpPort" 
                      noStyle
                      rules={[
                        ({ getFieldValue }) => ({
                          validator(_, value) {
                            if (!getFieldValue('enableMapping') || value) {
                              return Promise.resolve();
                            }
                            return Promise.reject(new Error('请输入本地端口'));
                          },
                        }),
                      ]}
                    >
                      <Input 
                        placeholder="7779"
                        style={{ width: '50%' }}
                        className="bg-dark-secondary border-dark-border text-text-primary"
                      />
                    </Form.Item>
                    <Form.Item 
                      name="remoteTcpPort" 
                      noStyle
                      rules={[
                        ({ getFieldValue }) => ({
                          validator(_, value) {
                            if (!getFieldValue('enableMapping') || value) {
                              return Promise.resolve();
                            }
                            return Promise.reject(new Error('请输入远程端口'));
                          },
                        }),
                      ]}
                    >
                      <Input 
                        placeholder="远程端口"
                        style={{ width: '50%' }}
                        className="bg-dark-secondary border-dark-border text-text-primary"
                      />
                    </Form.Item>
                  </Input.Group>
                </Form.Item>

                <Form.Item 
                  label="启用端口映射" 
                  name="enableMapping"
                  valuePropName="checked"
                >
                  <Switch />
                </Form.Item>
              </Card>
            </Form>
          </div>
        );
      default:
        return null;
    }
  };

  return (
    <motion.div 
      initial={{ opacity: 0, y: 20 }} 
      animate={{ opacity: 1, y: 0 }} 
      transition={{ duration: 0.6 }}
      className="space-y-6"
    >
      <div className="card-container">
        <Card className="card">
          <div className="text-center space-y-4 mb-8">
            <h1 className="text-gradient text-3xl font-bold">Ac.God.Panel - FRP 配置向导</h1>
            <p className="text-text-secondary text-lg">选择安装位置并自动下载配置 FRP 客户端，实现内网穿透</p>
          </div>

          <Steps current={currentStep} className="mb-8">
            <Step title="选择安装位置" icon={<FolderOpen size={20} />} />
            <Step title="部署 FRP" icon={<Download size={20} />} />
            <Step title="配置 FRP" icon={<Settings size={20} />} />
          </Steps>

          <div className="card-container">
            {renderStepContent()}
          </div>

          <div className="flex justify-center space-x-4 mt-6">
            {currentStep > 0 && currentStep < 2 && !isInstalling && (
              <Button size="large" className="btn-secondary" onClick={handlePrev}>
                上一步
              </Button>
            )}
            {currentStep === 0 && (
              <Button 
                type="primary" 
                size="large" 
                className="btn-primary"
                onClick={handleNext}
                disabled={!installPath.trim()}
              >
                下一步
              </Button>
            )}
            {currentStep === 1 && (
              <Button 
                type="primary" 
                size="large" 
                className="btn-primary"
                loading={isInstalling}
                disabled={isInstalling}
              >
                {isInstalling ? '下载中...' : '等待下载完成'}
              </Button>
            )}
            {currentStep === 2 && (
              <Button 
                type="primary" 
                size="large" 
                className="btn-primary"
                onClick={handleNext}
              >
                保存配置
              </Button>
            )}
          </div>
        </Card>
      </div>
    </motion.div>
  );
};

export default FrpSetup; 